package com.caltco.cargo.ops.config;

        import jakarta.servlet.*;
        import jakarta.servlet.http.HttpServletRequest;
        import jakarta.servlet.http.HttpServletResponse;
        import org.springframework.beans.factory.annotation.Value;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.core.Ordered;
        import org.springframework.core.annotation.Order;

        import java.io.IOException;

/**
 * @program: CameraServer
 * @description: 跨域访问配置
 * @author: yaolong
 * @create: 2021-04-20 15:50
 **/
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
public class CorsFilter implements Filter {
    @Value("${multimodule.open}")
    private Boolean isModule;

    // 允许的前端地址，可以根据需要配置多个
    @Value("${cors.allowed.origins}") // 从配置文件中读取允许的源
    private String allowedOrigins;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //log.error("我被注入啦！");
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", allowedOrigins);//不可以传*
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD,PUT, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",  "access-control-allow-origin, Authorization, authority, content-type, version-info, X-Requested-With, istoken");        response.setHeader("Access-Control-Allow-Credentials", "true");//这行是关键
        HttpServletRequest request = (HttpServletRequest)req;
        if("OPTIONS".equalsIgnoreCase(request.getMethod())){
            response.setStatus(HttpServletResponse.SC_OK);
        }else{
            chain.doFilter(req,res);
        }
    }

    @Override
    public void destroy() {
        // Cleanup code if necessary
    }
}
